package com.liu.yupao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liu.yupao.common.BaseResponse;
import com.liu.yupao.common.ErrorCode;
import com.liu.yupao.common.ResultUtils;
import com.liu.yupao.exception.BusinessException;
import com.liu.yupao.model.dto.team.*;
import com.liu.yupao.model.entity.Team;
import com.liu.yupao.model.entity.User;
import com.liu.yupao.model.entity.UserTeam;
import com.liu.yupao.model.vo.TeamUserVO;
import com.liu.yupao.service.TeamService;
import com.liu.yupao.service.UserService;
import com.liu.yupao.service.UserTeamService;
import lombok.extern.slf4j.Slf4j;


import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author lqh
 * @since 2025-10-11 21:06
 * 队伍控制器
 */
@RequestMapping("/team")
@RestController
@Slf4j
public class TeamController {

    @Resource
    private TeamService teamService;

    @Resource
    private UserService userService;

    @Resource
    private UserTeamService userTeamService;

    @PostMapping("/add")
    public BaseResponse<Long> addTeam(@RequestBody TeamAddRequest teamAddRequest, HttpServletRequest request){
        //判断是否为null
        if (teamAddRequest==null){
            throw new BusinessException (ErrorCode.PARAMS_ERROR);
        }
        return ResultUtils.success (teamService.addTeam (teamAddRequest,request));
    }

    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteTeam(@RequestParam long teamId){
        if (teamId<=0){
            throw new BusinessException (ErrorCode.PARAMS_ERROR);
        }
        //执行删除操作
        return ResultUtils.success (teamService.deleteTeam(teamId));
    }

    @GetMapping("/list")
    public BaseResponse<List<TeamUserVO>> listTeams(TeamQueryRequest teamQueryRequest,HttpServletRequest request){
        if (teamQueryRequest==null){
            throw new BusinessException (ErrorCode.PARAMS_ERROR);
        }
        //执行查询
        return ResultUtils.success (teamService.queryTeams(teamQueryRequest,request,false));

    }

    @GetMapping("/get")
    public BaseResponse<TeamUserVO> getTeamById(long teamId){
        if (teamId<=0){
            throw new BusinessException (ErrorCode.PARAMS_ERROR);
        }
        Team team = teamService.getById (teamId);
        if (team==null){
            throw new BusinessException (ErrorCode.NULL_ERROR);
        }
        return ResultUtils.success (TeamUserVO.toTeamVO (team));
    }

    @PostMapping("/update")
    public BaseResponse<Boolean> updateTeam(@RequestBody TeamUpdateRequest teamUpdateRequest,HttpServletRequest request){
        if(teamUpdateRequest==null || teamUpdateRequest.getId ()<=0){
            throw new BusinessException (ErrorCode.PARAMS_ERROR);
        }
        //执行更新操作
        return ResultUtils.success (teamService.updateUser(teamUpdateRequest,request));
    }

    @PostMapping("/join")
    public BaseResponse<Boolean> joinTeam(@RequestBody TeamJoinRequest teamJoinRequest, HttpServletRequest request){
        Long teamId = teamJoinRequest.getTeamId ();
        String password = teamJoinRequest.getPassword ();
        if (teamId==null || teamId<=0){
            throw new BusinessException (ErrorCode.PARAMS_ERROR);
        }
        return ResultUtils.success (teamService.joinTeam (teamId, password, request));

    }

    @PostMapping("/quit")
    public BaseResponse<Boolean> exitTeam(@RequestBody TeamQuitRequest teamQuitRequest, HttpServletRequest request){
        Long teamId = teamQuitRequest.getTeamId ();
        //校验参数
        if (teamId==null || teamId<=0){
            throw new BusinessException (ErrorCode.PARAMS_ERROR,"参数错误!");
        }
        return ResultUtils.success (teamService.exitTeam (teamId,request));
    }

    @PostMapping("/release")
    public BaseResponse<Boolean> releaseTeam(@RequestBody TeamReleaseRequest teamReleaseRequest,HttpServletRequest request) {
        //校验参数
        Long teamId = teamReleaseRequest.getTeamId ();
        if (teamId==null || teamId<=0){
            throw new BusinessException (ErrorCode.PARAMS_ERROR);
        }

       return ResultUtils.success ( teamService.releaseTeam(teamId,request));
    }

    /**
     * 获取自己创建的队伍
     */
    @GetMapping("/list/my/creat")
    public BaseResponse<List<TeamUserVO>> listMyCreatTeams(TeamQueryRequest teamQueryRequest,HttpServletRequest request){
        if (teamQueryRequest==null){
            throw new BusinessException (ErrorCode.PARAMS_ERROR);
        }
        //获取当前登录用户
        User loginUser = userService.getLoginUser (request);
        teamQueryRequest.setUserId (loginUser.getId ());
        //执行查询
        return ResultUtils.success (teamService.queryTeams(teamQueryRequest,request,false));

    }

    /**
     * 获取自己加入的队伍(不包含自己创建的)
     */
    @GetMapping("/list/my/join")
    public BaseResponse<List<TeamUserVO>> listMyJoinTeams(TeamQueryRequest teamQueryRequest,HttpServletRequest request){
        if (teamQueryRequest==null){
            throw new BusinessException (ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser (request);

        //查询自己加入队伍的队伍id
        QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<> ();
        queryWrapper.eq ("userId",loginUser.getId ());
        List<UserTeam> userTeamList = userTeamService.list (queryWrapper);
        //获取队伍id
        Map<Long, List<UserTeam>> collect = userTeamList.stream ().collect (Collectors.groupingBy (UserTeam::getTeamId));
        List<Long> ids = new ArrayList<> (collect.keySet ());
        //获取自己建立的队伍
        Team team = new Team ();
        team.setUserId (loginUser.getId ());
        QueryWrapper<Team> teamQueryWrapper = new QueryWrapper<> (team);
        List<Team> list = teamService.list (teamQueryWrapper);
        List<Long> myIdList = list.stream ().map (Team::getId).collect (Collectors.toList ());
        List<Long> newIds = ids.stream ().filter (id -> !myIdList.contains (id)).collect (Collectors.toList ());
        teamQueryRequest.setIdList (newIds);
        //执行查询
        return ResultUtils.success (teamService.queryTeams (teamQueryRequest,request,true));

    }

    /**
     * 获取自己加入的队伍列表（包含自己）
     */
    @GetMapping("/list/my/join/include")
    public BaseResponse<List<TeamUserVO>> listMyIncludeMyTeams(TeamQueryRequest teamQueryRequest,HttpServletRequest request){
        if (teamQueryRequest==null){
            throw new BusinessException (ErrorCode.PARAMS_ERROR);
        }
        //获取当前登录用户
        User loginUser = userService.getLoginUser (request);
        //获取自己加入的队伍(包括自己)
        QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<> ();
        //优化一下 只需要队伍id即可
        userTeamQueryWrapper.select ("teamId");
        userTeamQueryWrapper.eq ("userId",loginUser.getId ());
        List<UserTeam> list = userTeamService.list (userTeamQueryWrapper);
        //收集队伍id
        List<Long> joinTeamIds = list.stream ().map (UserTeam::getTeamId).collect (Collectors.toList ());
        //放入查询信息中
        teamQueryRequest.setIdList (joinTeamIds);
        List<TeamUserVO> teamUserVOS = teamService.queryTeams (teamQueryRequest, request,true);
        return ResultUtils.success (teamUserVOS);
    }

}
